﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SF.Base.Core;
using System.Text.RegularExpressions;

namespace SF.Dict.Web
{
	public partial class Dict : BasePage
	{
		protected long Did{
			get;
			set;
		}
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				string w = Request.GetStr("w");
				
				Did = 0;
				DictEntity Dict = null;
				if (string.IsNullOrEmpty(w)) {
					Did = Request.GetInt("i");
					if (Did > 0) {
						Dict = DictRules.GetDictByDidFromCache(Did);
					}
				}
				else{
					Dict = DictRules.GetDictBySpellFromCache(w);
					Did = Dict.Did;
				}

				if (Global.DTUser == null) {
					Response.Redirect("/login.aspx?return=" + Server.UrlEncode(string.Format("/dict.aspx?i={0}", Did)));
				}
				
				if (Dict != null)
				{
					w = Dict.ASpell;
					ll_title.Text = w + " | 挚友云海 | 收获于学习之外";
					string admin = Request.GetStr("a");

					//如何此单词存在
					lbl_spell.Text = Dict.ASpell;

					ltl_paraphrase.Text = StringHelper.EncodeToHtml(Dict.Paraphrase);
					
					string pron = Regex.Replace(Dict.APronunciation, @"\|", "<img border=\"0\" alt=\"\" src=\"/Common/images/compart.png\" class=\"compart\"/>");

					lbl_pron.Text = pron.Replace("<SUP>", "(").Replace("</SUP>", ")"); ;

					hf_did.Value = Dict.Did.ToString();

					CommentDataBind(Dict.DictId);

					VocabularyEntity Vocabulary = VocabularyRules.GetVocabularyByDictId(Dict.DictId);

					Boolean IsAdmin = (Vocabulary.UserId == UserId) ? true : false;

					UserEntity CreateUser = UserRules.GetUserByUserId(Vocabulary.UserId);

					//判断用户是否关注了本词汇表
					Boolean IsCollect = DictRules.IsCollect(UserId, Dict.DictId);

					if (!ClientScript.IsClientScriptBlockRegistered("Did")) {
						ClientScript.RegisterClientScriptBlock(Page.GetType(), "Did", "var oDict = {did:" + Did + ",adminid:" + CreateUser.UID + ",adminname:'" + CreateUser.NiceName + "',isadmin:" + IsAdmin.ToString().ToLower() + ",iscollect:" + IsCollect.ToString().ToLower() + "};", true);
					}

				}
				else
				{
					//如何此单词不存在，新增单词
					Logger.Detail("单词不存在");
					//Response.Redirect(string.Format("/Nonexistent.aspx?w={0}",w),true);
				}
			}
		}

		protected void CommentDataBind(List<CommentEntity> comments)
		{
			//处理单词评论
			rp_comments.DataSource = comments;
			rp_comments.DataBind();

			lbl_commentcount.Text = comments.Count.ToString();

			Logger.Detail(comments.Count);
		}

		protected void CommentDataBind(string DictId)
		{
			List<CommentEntity> comments = CommentRules.GetFirstLevelCommentsByObjectId(DictId, "comment",UserId);
			CommentDataBind(comments);
		}
	}
}